// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        user:{
            default: null,
            type: cc.Node,
        },
        //拾取范围
        pickRadius: 50,
        //



    },

    

    onLoad () {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
        this.pick=false;
        this.throw=false;
    },

    start () {

    },

    update (dt) {

        if (this.userDistance() < this.pickRadius) {
            if (this.pick) {
                this.pickUp();
            };
            if(this.throw){
                this.throwOut();
            };
        };
    },


    onKeyDown (event) {
        switch(event.keyCode) {
            case cc.macro.KEY.k:
                this.pick=true;
                break;
                
                
        }
    },
    onKeyUp (event) {
        // unset a flag when key released
        switch(event.keyCode) {
            case cc.macro.KEY.k:
                this.throw=true;
                break;
                
        }
    },    



    //获取user和brick距离
    userDistance:function(){
        var UserPos = cc.v2(this.user.x, this.user.y + this.user.height/2);
        
         // 根据两点位置计算两点之间距离
        var dist = this.node.position.sub(UserPos).mag();
        return dist;
    },
    
    pickUp:function(){
        this.node.x=this.user.x;
        this.node.y=this.user.y+85;
    },
    throwOut:function(){
        var uP= this.user.getPosition();
        var nP=this.node.getPosition();
        if(this.user.scaleX=-1){

                cc.tween(this.node)
              .to(0.5, {angle:50, position: cc.v2(uP.x-50,  nP.y+100)})
              .to(1, {angle: 100, position: cc.v2(uP.x-100,  nP.y)})
              .to(1.5, {angle:50, position: cc.v2(uP.x-100,  nP.y)})
              .to(2, {angle: 0, position: cc.v2(uP.x-180,  nP.y)})
              .start(cc.find('Canvas/cocos'));
        }else{
            cc.tween(this.node)
              .to(0.5, { position: cc.v2(uP.x-50,  usPo+100)})
              .to(1, { position: cc.v2(uP.x-100,  usPo)})
              .to(1.5, { position: cc.v2(uP.x-100,  usPo)})
              .to(2, { position: cc.v2(uP.x-180,  usPo)})
              .start(cc.find('Canvas/cocos'));
        };
        
        
    },

});
